import { PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns, ProDescriptionsItemProps } from '@ant-design/pro-components';
import {
  FooterToolbar,
  ModalForm,
  PageContainer,
  ProDescriptions,
  ProFormSelect,
  ProFormText,
  ProFormTextArea,
  ProFormInstance,
  ProTable,
} from '@ant-design/pro-components';
import { Button, Drawer, Input, message } from 'antd';
import React, { useRef, useState } from 'react';
import { FormattedMessage, useIntl } from 'umi';
import { getColumns } from './config';
import * as mockApi from '@/services/mockApi';
import { useEffect } from 'react';

/**
 * @en-US Add node
 * @zh-CN 模块
 * @param fields
 */
const handleAdd = async (fields: any) => {
  const msg = fields.id ? '编辑' : '添加';
  const hide = message.loading(`正在${msg}`);
  try {
    if (fields.id) {
      await mockApi.updateLowcodeModuleName({ ...fields });
    } else {
      await mockApi.addLowcodeModule({ ...fields });
    }
    hide();
    message.success(`${msg}成功！`);
    return true;
  } catch (error) {
    hide();
    message.error(`${msg}失败！`);
    return false;
  }
};

const handleDelete = async (id: number) => {
  const hide = message.loading(`正在删除`);
  try {
    mockApi.deleteModuleById(id);
    hide();
    message.success(`删除成功！`);
    return true;
  } catch (error) {
    hide();
    message.error(`删除失败！`);
    return false;
  }
};

const moduleRelease = async (fields: any) => {
  const hide = message.loading(`正在发布`);
  try {
    await mockApi.moduleRelease({ ...fields });
    hide();
    message.success(`发布成功！`);
    return true;
  } catch (error) {
    hide();
    message.error(`发布失败！`);
    return false;
  }
};

const TableList: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState();
  const [releaseRow, setReleseRow] = useState();
  const modalFormRef = useRef<ProFormInstance>();
  const [formDisabled, setFormDisabled] = useState<boolean>(false);
  const modalReleaseFormRef = useRef<ProFormInstance>();
  /**
   * @en-US Pop-up window of new window
   * @zh-CN 新建窗口的弹窗
   *  */
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const [releaseFormVisible, handleReleaseFormVisible] = useState<boolean>(false);

  /**
   * @en-US International configuration
   * @zh-CN 国际化配置
   * */
  const intl = useIntl();

  useEffect(() => {
    if (createModalVisible) {
      if (currentRow) {
        modalFormRef.current.setFieldsValue(currentRow);
        setFormDisabled(true);
      } else {
        setFormDisabled(false);
        modalFormRef.current.resetFields();
      }
    }
  }, [currentRow, createModalVisible]);
  useEffect(() => {
    if (releaseFormVisible && releaseRow) {
      modalReleaseFormRef.current?.setFieldsValue(releaseRow);
    }
  }, [releaseRow, releaseFormVisible]);

  return (
    <PageContainer header={{ title: '' }}>
      <ProTable<any, API.PageParams>
        actionRef={actionRef}
        rowKey="key"
        search={{
          labelWidth: 120,
        }}
        request={async (
          // 第一个参数 params 查询表单和 params 参数的结合
          // 第一个参数中一定会有 pageSize 和  current ，这两个参数是 antd 的规范
          params,
          sort,
          filter,
        ) => {
          // 这里需要返回一个 Promise,在返回之前你可以进行数据转化
          // 如果需要转化参数可以在这里进行修改
          const msg = await mockApi.getLowcodeModuleList();
          return {
            data: msg.data,
            // success 请返回 true，
            // 不然 table 会停止解析数据，即使有数据
            success: msg.success,
            // 不传会使用 data 的长度，如果是分页一定要传
            //total: number,
          };
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              setCurrentRow(undefined);
              handleModalVisible(true);
            }}
          >
            <PlusOutlined /> <FormattedMessage id="pages.searchTable.new" defaultMessage="New" />
          </Button>,
        ]}
        columns={getColumns({
          handleModalVisible,
          setCurrentRow,
          handleReleaseFormVisible,
          setReleseRow,
          deleteRow: async (id: number) => {
            const success = await handleDelete(id);
            if (success) {
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          },
        })}
      />
      <ModalForm
        formRef={modalFormRef}
        title={intl.formatMessage({
          id: 'pages.data.newModule',
          //defaultMessage: '新建模块',
        })}
        width="400px"
        visible={createModalVisible}
        onVisibleChange={handleModalVisible}
        onFinish={async (value) => {
          const success = await handleAdd(value);
          if (success) {
            handleModalVisible(false);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
      >
        <ProFormText
          label={'模块名称'}
          rules={[
            {
              required: true,
              message: '名称不能为空',
            },
          ]}
          width="md"
          name="name"
        />
        <ProFormSelect
          label={'组件库'}
          rules={[
            {
              required: true,
              message: '请选择组件库',
            },
          ]}
          options={[
            { label: 'antd', value: 'antd' },
            { label: 'Fusion-UI', value: 'Fusion-UI' },
          ]}
          width="md"
          disabled={formDisabled}
          name="assets"
        />
        <ProFormText label={'模块ID'} hidden={true} width="md" name="id" />
      </ModalForm>
      <ModalForm
        formRef={modalReleaseFormRef}
        title={intl.formatMessage({
          id: 'pages.data.release',
        })}
        width="400px"
        visible={releaseFormVisible}
        onVisibleChange={handleReleaseFormVisible}
        onFinish={async (value) => {
          const success = await moduleRelease(value);
          if (success) {
            modalReleaseFormRef.current?.resetFields();
            handleReleaseFormVisible(false);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
      >
        <ProFormText label={'模块名称'} width="md" name="name" readonly={true} />
        <ProFormText
          label={'版本号'}
          rules={[
            {
              required: true,
              message: '请输入版本号',
            },
          ]}
          width="md"
          name="vesion"
        />

        <ProFormTextArea
          label={'版本备注'}
          rules={[
            {
              //required: true,
              max: 200,
              message: '请输入版本号',
            },
          ]}
          width="md"
          name="remark"
        />
        <ProFormText label={'模块ID'} hidden={true} width="md" name="id" />
      </ModalForm>
    </PageContainer>
  );
};

export default TableList;
